package com.weiyin.examination.course;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.chad.library.adapter.base.BaseViewHolder;
import com.weiyin.examination.R;
import com.weiyin.examination.adapter.Bottom1Adapter;
import com.weiyin.examination.adapter.BottomAdapter;
import com.weiyin.examination.application.Constant;
import com.weiyin.examination.application.ResId;
import com.weiyin.examination.dialog.BottomDialog;
import com.weiyin.examination.dialog.FlatSharpDialog;
import com.weiyin.examination.listener.CourseInterface;
import com.weiyin.examination.listener.DialogResultInterface;
import com.weiyin.examination.listener.DialogShowListener;
import com.weiyin.examination.module.AnswerModule;
import com.weiyin.examination.module.AnswerXml;
import com.weiyin.examination.module.BottomModule;
import com.weiyin.examination.module.Note;
import com.weiyin.examination.module.TestModule;
import com.weiyin.examination.util.LayoutHelper;
import com.weiyin.examination.util.LogUtil;
import com.weiyin.examination.util.SPUtil;
import com.weiyin.examination.view.CourseView;
import com.weiyin.examination.view.GridLayoutManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author njf
 *         Created by lenovo on 2017/9/18.
 */

public class CourseA6 extends Course implements BottomAdapter.OnItemClickInterface, Bottom1Adapter.OnItemClickInterface {
    private View rootView;
    private Activity activity;
    private ClickAble clickAble;

    private RecyclerView bottomRecyclerView, bottomRecyclerView1;
    private Bottom1Adapter bottom1Adapter;
    private BottomAdapter bottomAdapter;

    private TextView titleLayoutNextTextView, titleLayoutLastTextView, titleLayoutSubjectContentTextView, titleLayoutSubjectScoreTextView,
            titleLayoutNumberTextView, titleTicketNumber;
    private RelativeLayout titleLayoutNumberRl;
    private ImageView courseA9FlatSharp;

    private TestModule testModule;
    private List<TestModule> testModuleList;
    private List<AnswerModule> answerModuleList;
    private int courseIndex;
    private Handler mHandler = new Handler();
    private CourseView courseView;
    private int bottomIndex = -1, riseDropIndex = -1;

    private boolean isRepose = false;
    private boolean spot = false, homoPhonicConnection = false, threeNote = false, clef = true;
    private List<BottomModule> integerList;
    private List<String> stringList;
    private int mark = 0;
    private View view, view1;
    private LayoutHelper layoutHelper;

    private ResId resId;

    private boolean click = false;
    private double score;

    @Override
    public void onCreate(Activity activity, ViewFlipper contain, List<TestModule> courseEntities, int index) {
        if (rootView == null) {
            rootView = LayoutInflater.from(activity).inflate(R.layout.coursea6_layout, null);

            layoutHelper = new LayoutHelper(activity);
            layoutHelper.scaleView(rootView);

            resId = new ResId();
            contain.addView(rootView);
            this.testModuleList = courseEntities;
            this.activity = activity;
            this.courseIndex = index;
            this.testModule = testModuleList.get(index);
            clickAble = new ClickAble();
            getImage();
            if (testModule != null) {
                if (testModule.getRightAnswerList() != null) {
                    this.answerModuleList = testModule.getRightAnswerList();
                }
            }
            initView();
        }
    }

    private void getImage() {
        if (integerList == null) {
            integerList = new ArrayList<>();
        }
        for (int i = 0; i < resId.getImageId().length; i++) {
            BottomModule bottomModule = new BottomModule();
            bottomModule.setBitmapId(resId.getImageId()[i]);
            bottomModule.setGreyBitmapId(resId.getGreyImageId()[i]);
            if (i == 0 || i == 2 || i == 3 || i == 4 || i == 5 || i == 11 || i == 12 || i == 13 || i == 14 || i == 15) {
                bottomModule.setClick(false);
            } else {
                bottomModule.setClick(true);
            }
            integerList.add(bottomModule);
        }
        if (stringList == null) {
            stringList = new ArrayList<>();
        }
        Collections.addAll(stringList, resId.getStringId());
    }

    @Override
    public void initView() {
        titleLayoutNextTextView = (TextView) rootView.findViewById(R.id.titleLayoutNextTextView);
        titleLayoutLastTextView = (TextView) rootView.findViewById(R.id.titleLayoutLastTextView);
        titleLayoutSubjectContentTextView = (TextView) rootView.findViewById(R.id.titleLayoutSubjectContentTextView);
        titleLayoutSubjectScoreTextView = (TextView) rootView.findViewById(R.id.titleLayoutSubjectScoreTextView);
        titleLayoutNumberTextView = (TextView) rootView.findViewById(R.id.titleLayoutNumberTextView);
        courseView = (CourseView) rootView.findViewById(R.id.courseA5CourseView);
        titleTicketNumber = (TextView) rootView.findViewById(R.id.titleTicketNumber);
        courseA9FlatSharp = (ImageView) rootView.findViewById(R.id.courseA9FlatSharp);
        titleLayoutNumberRl = (RelativeLayout) rootView.findViewById(R.id.titleLayoutNumberRl);

        bottomRecyclerView = (RecyclerView) rootView.findViewById(R.id.bottomRecyclerView);
        bottomAdapter = new BottomAdapter(activity, R.layout.coursea5_item_layout, integerList);
        bottomRecyclerView.setLayoutManager(new GridLayoutManager(activity, integerList.size(), LinearLayoutManager.VERTICAL, false));
        bottomRecyclerView.setAdapter(bottomAdapter);

        bottomRecyclerView1 = (RecyclerView) rootView.findViewById(R.id.bottomRecyclerView1);
        bottomRecyclerView1.setVisibility(View.VISIBLE);
        bottom1Adapter = new Bottom1Adapter(activity, R.layout.bottom_item_layout, stringList);
        bottomRecyclerView1.setAdapter(bottom1Adapter);
        bottomRecyclerView1.setLayoutManager(new GridLayoutManager(activity, stringList.size(), LinearLayoutManager.VERTICAL, false));
        bottom1Adapter.setOnItemClickInterface(this);

        bottomAdapter.setOnItemClickInterface(this);
        courseA9FlatSharp.setOnClickListener(clickAble);
        titleLayoutNextTextView.setOnClickListener(clickAble);
        titleLayoutLastTextView.setOnClickListener(clickAble);
        titleLayoutNumberRl.setOnClickListener(clickAble);

        courseView.setPitchX(5);
        courseView.setCourseViewListener(new CourseView.CourseViewListener() {
            @Override
            public void courseViewResult(int type) {
                if (1 == type) {
                    mark = 0;
                    if (view1 != null) {
                        view1.setSelected(false);
                    }
                    LogUtil.i(TAG, "courseViewResult");
                }
                if (4 == type) {
                    if (view != null) {
                        view.setSelected(false);
                        setClick(true);
                    }
                }
            }
        });
    }

    @SuppressLint("SetTextI18n")
    private void initViewData() {
        if (testModule != null) {
            if ("1".equals(testModule.getbTemporaryKey())) {
                courseA9FlatSharp.setVisibility(View.GONE);
            } else {
                courseA9FlatSharp.setVisibility(View.VISIBLE);
            }
            courseA9FlatSharp.setVisibility(("1".equals(testModule.getbTemporaryKey()) ? View.GONE : View.VISIBLE));
            LogUtil.i(TAG, "testModule.getbTemporaryKey()=" + testModule.getbTemporaryKey());
            titleTicketNumber.setText("准考证号：" + "" + testModule.getTickNumber());

            titleLayoutLastTextView.setVisibility(courseIndex == 0 ? View.GONE : View.VISIBLE);
            titleLayoutNextTextView.setVisibility(courseIndex == testModuleList.size() - 1 ? View.GONE : View.VISIBLE);

            titleLayoutSubjectContentTextView.setText((courseIndex + 1) + "丶" + testModule.getSubjectTitle());
            titleLayoutSubjectScoreTextView.setText("（" + testModule.getScore() + "分）");
            titleLayoutNumberTextView.setText("第" + (courseIndex + 1) + "题/第" + (testModuleList.size()) + "题");
        }
    }

    private void showDialog() {
        BottomDialog bottomDialog = new BottomDialog(activity, R.style.base_loading_dialogfragment);
        Window window = bottomDialog.getWindow();
        assert window != null;
        WindowManager.LayoutParams p = window.getAttributes();
        Display d = window.getWindowManager().getDefaultDisplay();
        window.setGravity(Gravity.LEFT);

        p.x = 0;
        LogUtil.i(TAG, "d.getHeight()=" + d.getHeight() + " y=" + layoutHelper.scaleDimension(100, "y"));
        p.y = (d.getHeight() / 2 - layoutHelper.scaleDimension(200, "y"));
        window.setAttributes(p);
        bottomDialog.setDialogResultInterface(new DialogResultInterface() {
            @Override
            public void result(String type, String result, String answerId) {
                if (Constant.BOTTOM_RESULT.equals(type)) {
                    if (Constant.BOTTOM_DISMISS.equals(result)) {
                        integerList.get(0).setBitmapId(R.drawable.buttom1_down);
                        bottomAdapter.notifyDataSetChanged();
                    } else if (Constant.BOTTOM_END.equals(result)) {
                        clef = false;
                        courseView.setCurImg(bottomIndex, true, isRepose, spot, mark, homoPhonicConnection, threeNote, false);
                        courseView.invalidate();
                    } else if (Constant.BOTTOM_START.equals(result)) {
                        clef = true;
                        courseView.setCurImg(bottomIndex, true, isRepose, spot, mark, homoPhonicConnection, threeNote, true);
                        courseView.invalidate();
                    }
                }
            }
        });
        bottomDialog.show();
    }

    private void showFlatSharpDialog(final ImageView view, boolean type) {
        FlatSharpDialog flatSharpDialog = new FlatSharpDialog(activity, R.style.base_loading_dialogfragment, type);
        Window window = flatSharpDialog.getWindow();
        assert window != null;
        WindowManager.LayoutParams p = window.getAttributes();
        Display d = window.getWindowManager().getDefaultDisplay();
        window.setGravity(Gravity.LEFT | Gravity.TOP);
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        // 新位置X坐标
        p.x = view.getWidth() / 2;
        // 新位置Y坐标
        p.y = location[1];
        window.setAttributes(p);
        flatSharpDialog.show();
        flatSharpDialog.setDialogResultInterface(new DialogResultInterface() {
            @Override
            public void result(String type, String result, String answerId) {
                riseDropIndex = Integer.valueOf(result);
                LogUtil.i(TAG, "riseDropIndex=" + riseDropIndex);
                if (Constant.COURSE_A9_DIALOG_RESULT1.equals(type)) {
                    view.setImageResource(resId.getFateId()[riseDropIndex]);
                    courseView.setFlatIndex(riseDropIndex);
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
                    if (!clef) {
                        if (riseDropIndex < 7) {
                            layoutParams.topMargin = layoutHelper.scaleDimension(177, "y");
                        } else {
                            layoutParams.topMargin = layoutHelper.scaleDimension(173, "y");
                        }
                    } else {
                        if (riseDropIndex < 7) {
                            layoutParams.topMargin = layoutHelper.scaleDimension(163, "y");
                        } else {
                            layoutParams.topMargin = layoutHelper.scaleDimension(151, "y");
                        }
                    }
                } else if (Constant.COURSE_A9_DIALOG_RESULT2.equals(type)) {
                    view.setImageResource(resId.getTimeImageId()[Integer.valueOf(result)]);
                    if (riseDropIndex == 0 || riseDropIndex == 1 || riseDropIndex == 3) {
                        courseView.setNoteType(4);
                        courseView.setLineType(true);
                    } else {
                        courseView.setNoteType(3);
                        courseView.setLineType(true);
                    }
                }
            }
        });
    }

    private void setClick(boolean setCurImg) {
        if (view != null) {
            if (setCurImg) {
                view.setSelected(false);
            }
            if (!view.isSelected()) {
                LogUtil.i(TAG, " click = false");
                click = false;
                if (setCurImg)
                    courseView.setCurImg(17, click, isRepose, spot, mark, homoPhonicConnection, threeNote, clef);
            }
        }
    }

    @Override
    public void onItemClick(BaseViewHolder holder, int position) {
        View viewLayout = holder.getView(R.id.courseA5ItemLayout);
        switch (position) {
            case 0:
                integerList.get(0).setBitmapId(R.drawable.buttom1_up);
                bottomAdapter.notifyDataSetChanged();
                showDialog();
                break;
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
                this.bottomIndex = position;
                click = true;
                viewLayout.setSelected(!viewLayout.isSelected());
                if (view != null && view.getX() != viewLayout.getX()) {
                    view.setSelected(false);
                } else {
                    setClick(false);
                }
                view = viewLayout;
                break;
            case 6:
            case 7:
            case 8:
            case 9:
            case 10:
                if (mark != position) {
                    mark = position;
                } else {
                    mark = 0;
                }
                viewLayout.setSelected(!viewLayout.isSelected());
                if (view1 != null && view1.getX() != viewLayout.getX()) {
                    view1.setSelected(false);
                }
                view1 = viewLayout;
                break;
            case 11:
                spot = !spot;
                threeNote = false;
                homoPhonicConnection = false;
                viewLayout.setSelected(!viewLayout.isSelected());
                break;
            case 13:
                threeNote = !threeNote;
                spot = false;
                homoPhonicConnection = false;
                viewLayout.setSelected(!viewLayout.isSelected());
                break;
            case 14:
                spot = false;
                threeNote = false;
                homoPhonicConnection = false;
                viewLayout.setSelected(!viewLayout.isSelected());
                break;
            case 15:
                spot = false;
                threeNote = false;
                homoPhonicConnection = !homoPhonicConnection;
                viewLayout.setSelected(!viewLayout.isSelected());
                break;
            case 16:
                courseView.setCurImg(position, true, isRepose, spot, mark, homoPhonicConnection, threeNote, clef);
                break;
            case 12:
//                viewLayout.setSelected(!viewLayout.isSelected());
//                bottomIndex = -1;
//                if (!isRepose) {
//                    isRepose = true;
//                    for (int i = 0; i < resId.getReposeId().length; i++) {
//                        bottomAdapter.setData(i + 1, new BottomModule(resId.getReposeId()[i], resId.getReposeId()[i], true));
//                    }
//                } else {
//                    isRepose = false;
//                    for (int i = 0; i < resId.getReposeId().length; i++) {
////                        integerList.get(i + 1).setBitmapId(resId.getImageId()[i + 1]);
//                        bottomAdapter.setData(i + 1, new BottomModule(resId.getImageId()[i + 1], resId.getImageId()[i + 1], true));
//                    }
//                }
                break;
            default:
                viewLayout.setSelected(!viewLayout.isSelected());
                break;
        }
        if (position != 16) {
            courseView.setCurImg(position, click, isRepose, spot, mark, homoPhonicConnection, threeNote, clef);
            if (position == 14 || (isRepose && (position == 1 || position == 2 || position == 3 || position == 4 || position == 5))) {
                courseView.setBitmap(position);
            }
        }
    }


    @Override
    public void onItemBottomClick(BaseViewHolder holder, int position) {
        View viewLayout = holder.getView(R.id.bottomItemLayoutTextView);
        switch (position) {
            case 0:
                courseView.setHighLow(7);
                break;
            case 8:
                courseView.setHighLow(-7);
                break;
            default:
                if (!isRepose) {
                    if (bottomIndex != -1) {
                        courseView.setCurImg(bottomIndex, click, isRepose, spot, mark, homoPhonicConnection, threeNote, clef);
                        if (click)
                            courseView.setBitmap(position);
                    }
                }
                break;
        }
    }

    class ClickAble implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.courseA9FlatSharp:
                    LogUtil.i(TAG, "courseA9FlatSharp");
                    showFlatSharpDialog(courseA9FlatSharp, false);
                    break;
                case R.id.titleLayoutNextTextView:
                    dialogShowListener.dialogShow(1, courseIndex, result());
                    courseInterface.courseInterfaceResult(Constant.NEXT_KNOWLEDGE, courseIndex + 1);
                    break;
                case R.id.titleLayoutLastTextView:
                    dialogShowListener.dialogShow(1, courseIndex, result());
                    courseInterface.courseInterfaceResult(Constant.LAST_KNOWLEDGE, courseIndex - 1);
                    break;
                case R.id.titleLayoutNumberRl:
                    dialogShowListener.dialogShow(1, courseIndex, result());
                    dialogShowListener.dialogShow(0, courseIndex, result());
                    break;
                default:
                    break;
            }
        }
    }

    private boolean result() {
        getScore();

        Constant.getScreen(activity, SPUtil.getSharedPreferencesData(activity, "number") + "_" + (courseIndex + 1),SPUtil.getSharedPreferencesData(activity, "number")+"_"+ (courseIndex + 1));
        if (courseView.getBitMapModuleList().size() > 0) {
            return true;
        } else {
            return false;
        }
    }

    private void getScore() {
        List<AnswerXml> list = answerModuleList.get(0).getAnswerXmlList();
        if (courseView == null) return;
        if (courseView.getAnswerXmlList().size() > 0) {


            List<Note> noteLists = courseView.getAnswerXmlList().get(0).getNoteList();
            if (list.size() > 0) {
                List<Note> noteList = list.get(0).getNoteList();
                for (int j = 0; j < noteList.size(); j++) {
                    Note note = noteList.get(j);
                    if (note.getNormalType() != null || note.getTied() != null) {
                        if (note.getNormalType() != null) {
                            if (j + 2 < noteList.size() && j + 2 < noteLists.size()) {
                                if (noteList.get(j + 2).equalsNote(noteLists.get(j + 2), true, false)) {
                                    score += Double.valueOf(answerModuleList.get(0).getScore()) / noteList.size();
                                }
                                if (noteList.get(j + 1).equalsNote(noteLists.get(j + 1), true, false)) {
                                    score += Double.valueOf(answerModuleList.get(0).getScore()) / noteList.size();
                                }
                                if (noteList.get(j).equalsNote(noteLists.get(j), true, false)) {
                                    score += Double.valueOf(answerModuleList.get(0).getScore()) / noteList.size();
                                }
                                j += 2;
                            } else {
                                if (j + 1 < noteList.size() && j + 1 < noteLists.size()) {
                                    if (noteList.get(j + 1).equalsNote(noteLists.get(j + 1), true, false)) {
                                        score += Double.valueOf(answerModuleList.get(0).getScore()) / noteList.size();
                                    }
                                    if (noteList.get(j).equalsNote(noteLists.get(j), true, false)) {
                                        score += Double.valueOf(answerModuleList.get(0).getScore()) / noteList.size();
                                    }
                                    j += 1;
                                } else {
                                    if (j < noteList.size() && j < noteLists.size()) {
                                        if (noteList.get(j).equalsNote(noteLists.get(j), true, false)) {
                                            score += Double.valueOf(answerModuleList.get(0).getScore()) / noteList.size();
                                        }
                                    }
                                }
                            }
                        } else {
                            if (j + 1 < noteList.size() && j + 1 < noteLists.size()) {
                                if (noteList.get(j + 1).equalsNote(noteLists.get(j + 1), false, true)) {
                                    score += Double.valueOf(answerModuleList.get(0).getScore()) / noteList.size();
                                }
                                if (j < noteList.size() && j < noteLists.size()) {
                                    if (note.equalsNote(noteLists.get(j), false, true)) {
                                        score += Double.valueOf(answerModuleList.get(0).getScore()) / noteList.size();
                                    }
                                }
                                j += 1;
                            } else {
                                if (j < noteList.size() && j < noteLists.size()) {
                                    if (note.equalsNote(noteLists.get(j), false, true)) {
                                        score += Double.valueOf(answerModuleList.get(0).getScore()) / noteList.size();
                                    }
                                }
                            }

                        }
                    } else {
                        if (note.equalsNote(noteLists.get(j), false, false)) {
                            score += Double.valueOf(answerModuleList.get(0).getScore()) / noteList.size();
                        }
                    }
                }
            }
        }
        SPUtil.setSharedPreferencesData(activity.getApplication(), CourseA6.class.getSimpleName(), score + "");
    }

    @Override
    public void setCourseInterface(CourseInterface courseInterface) {
        this.courseInterface = courseInterface;
    }

    @Override
    public void setCourseDialogListener(DialogShowListener dialogListener) {
        this.dialogShowListener = dialogListener;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    }

    @Override
    public void show(List<TestModule> courseEntities, int index, String type) {
        initViewData();
    }

    @Override
    public void stop() {

    }

    @Override
    public void destroy() {

    }
}
